const { sys_user, sys_role, sys_log, sys_menu, op } = require("../../middleware/baseModel");
const tokenService = require("../service/token");
const { getMd5 } = require("../../tool/funTool");
const dayjs = require("dayjs");

module.exports = {
  "GET /sys_user/index": async (ctx, next) => {
    const resList = await sys_user.findAll({
      where: {
        name: { [op.not]: "zc" },
      },
      include: [{ association: sys_user.associations.role, attributes: ["id", "name"] }],
    });
    return ctx.success(resList);
  },
  "POST /sys_user/login": async (ctx, next) => {
    let name = ctx.get("name");
    let password = ctx.get("password");

    const userRow = await sys_user.findOne({
      where: { name: name, password: getMd5(password) },
    });

    if (userRow) {
      let { id, name, password, roleId } = userRow;
      let role = await sys_role.findOne({ where: { id: roleId } });
      let token = await tokenService.create({ id, name, password });
      let nowDateStr = dayjs().format("YYYY-MM-DD HH:mm:ss");
      await sys_log.create({ table_name: "sys_user", operate: "登录", content: `用户<span class="bold"> ${name} </span> 于 ${nowDateStr} 登录系统` });
      return ctx.success({ token: token, user: userRow, authorityMenus: role.menus });
    }
    return ctx.fail("账号或密码错误!");
  },

  "POST /sys_user/export": async (ctx, next) => {
    let rows = [];
    let cols = [];
    let title = "sys_user";
    let tableAttributes = sys_user.tableAttributes;
    let colKeys = Object.keys(tableAttributes);

    colKeys.forEach((key) => {
      let row = tableAttributes[key];
      let caption = row.comment ? row.comment : row.fieldName;
      cols.push({ caption, type: row.type.__proto__.key === "INTEGER" ? "number" : "string", key: row.field });
    });

    const userRows = await sys_user.findAll({});

    rows = userRows.map((p) => {
      let tempRow = p.toJSON();
      let row = [];
      cols.forEach((col) => {
        row.push(tempRow[col.key]);
      });
      return row;
    });

    return ctx.downFile({ title, rows, cols });
  },

  "POST /sys_user/authorityMenus": async (ctx, next) => {
    let user_id = ctx.getAdminUserId();
    if (user_id) {
      const userRow = await sys_user.findOne({ where: { id: user_id } });
      if (userRow) {
        let { id, roleId } = userRow;

        let where = {};
        let role = await sys_role.findOne({ where: { id: roleId } });

        // 系统角色 不用授权
        if (role.type === 0) {
          let menuIds = JSON.parse(role.menus);
          where = {
            id: {
              [op.in]: menuIds,
            },
          };
        }
        let munuRows = await sys_menu.findAll({
          where,
          order: [["sort", "ASC"]],
        });

        return ctx.success(munuRows);
      }
    }

    return ctx.success();
  },

  "POST /sys_user/add": async (ctx, next) => {
    let row = ctx.getBody();

    // md5 加密
    if (row && row.password) {
      row.password = getMd5(row.password);
    }

    const res = await sys_user.create(row);
    return ctx.success(res);
  },
  "POST /sys_user/edit": async (ctx, next) => {
    let row = ctx.getBody();
    let id = ctx.get("id");

    let { name, roleId, password } = row;

    if (password.length !== 32) {
      password = getMd5(password);
    }

    const resList = await sys_user.update(
      { name, roleId, password },
      {
        where: {
          id: id,
        },
      }
    );
    return ctx.success(resList);
  },
  "POST /sys_user/del": async (ctx, next) => {
    let id = ctx.get("id");
    const res = await sys_user.destroy({
      where: {
        id: id,
      },
    });
    return ctx.success(res);
  },
};
